﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PBDesk.Utilities;
using umbraco.BusinessLogic;
using PBDesk.Umbraco.Helper;
using PBDesk.Business.Facebook;
using System.Collections;
using umbraco.cms.businesslogic.member;
using Newtonsoft.Json.Linq;
using System.Web.Security;

namespace PBDesk.Umbraco.Extension.Web.pages.FB
{
    /// <summary>
    /// Summary description for Facebook
    /// </summary>
    public class Facebook : IHttpHandler
    {
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            bool result = false;
            string pbLogon = context.Request.QueryString["pblogon"];
            if (pbLogon.IsNotNullAndNotEmpty())
            {
                Log.Add(LogTypes.Notify, -1, "Facebook.ashx - start - pblogon");
                result = DoPBLogon(context);
                context.Response.ContentType = "text/plain";
                context.Response.Write("ok");
            }
            else
            {
                Log.Add(LogTypes.Notify, -1, "Facebook.ashx - start - DeAuthorize");
                DoFBDeAuthorize(context);
            }

            
            
            
        }

        private void DoFBDeAuthorize(HttpContext context)
        {
            
            try
            {
                if (context.Request.Params["signed_request"] != null)
                {                    
                    string fbUserId = string.Empty;
                    string json = FBHelper.DecodeSignedRequest(context.Request.Params["signed_request"].ToString());
                    if (json.IsNotNullAndNotEmpty())
                    {
                        JObject jo = JObject.Parse(json);
                        if (jo != null)
                        {
                            fbUserId = (string)jo["user_id"];
                            UserManager.DeAuthorizeFacebookSubscriber(fbUserId);
                            Log.Add(LogTypes.Notify, -1, "Facebook.ashx(DeAuthorize): DeAuthorized Facebook user id: " + fbUserId);
                        }
                    }
                }
                else
                {
                    Log.Add(LogTypes.Notify, -1, "Facebook.ashx(DeAuthorize) Signed_Request is null");
                }
            }
            catch (Exception ex)
            {
                UmbHelper.WriteExceptionLog("Facebook.ashx(DeAuthorize) Error", ex);                
            }
            
        }

        private bool DoPBLogon(HttpContext context)
        {
            bool result = false;
            try
            {
                string fbCookie = CookieManager.GetCookieValue(FBApp.FBCookieName, false);
                if (fbCookie.IsNullOrEmpty())
                {
                    Log.Add(LogTypes.Notify, -1, "Facebook.ashx(pblogon) - Cookie not found. Expecting Cookie Value");
                }
                else
                {
                    fbCookie = fbCookie.Trim(new char[] { ' ', '\"' });
                    
                    Hashtable hTable = StringUtils.GetHashtableFromDelimatedString(fbCookie, "&", "=");                    
                    if (hTable != null && hTable.Count > 0)
                    {

                        string fbUID = string.Empty;
                        if (hTable["uid"] != null)
                        {
                            fbUID = hTable["uid"].ToString();
                            if (fbUID.IsNullOrEmpty())
                            {
                                Log.Add(LogTypes.Notify, -1, "Facebook.ashx(pblogon): Facebook user id is null or empty");
                            }
                            else
                            {
                                fbUID = UserManager.FACEBOOK_PREFIX + fbUID.Trim();
                                Member facebookSubscriber = null;
                                if (Member.IsMember(fbUID))
                                {
                                    facebookSubscriber = Member.GetMemberFromLoginName(fbUID);
                                    UserManager.UpdateFBAuthorizeStatus(facebookSubscriber);
                                }
                                else
                                {
                                    facebookSubscriber = CreateNewSubscriber(hTable);
                                }
                                if (facebookSubscriber != null)
                                {
                                    Member.AddMemberToCache(facebookSubscriber);
                                    FormsAuthentication.SetAuthCookie(facebookSubscriber.LoginName,false);
                                }
                                else
                                {
                                    Log.Add(LogTypes.Notify, -1, "Facebook.ashx(pblogon) Failure: Error in creating new member or retriving existing user");
                                }
                            }
                        }                                                
                    }
                }
            }
            catch (Exception ex)
            {
                UmbHelper.WriteExceptionLog("FBLogon.ashx - pblogon", ex);
            }

            return result;
        }

        private Member CreateNewSubscriber(Hashtable hTable)
        {
            Member newMember = null;
            string accessToken = String.Empty;
            if (hTable["access_token"] != null)
            {
                accessToken = hTable["access_token"].ToString();
                if (accessToken.IsNotNullAndNotEmpty())
                {
                    string me = FBHelper.GetME(accessToken);
                    if (me.IsNotNullAndNotEmpty())
                    {
                        JObject jo = JObject.Parse(me);
                        string fbUserId = (string)jo["id"] ?? string.Empty;
                        string fbUserName = (string)jo["name"] ?? string.Empty;
                        string email = (string)jo["email"] ?? string.Empty;
                        string gender = (string)jo["gender"] ?? string.Empty;
                        string location = string.Empty;
                        if (jo["location"] != null)
                        {
                            location = (string)jo["location"]["name"] ?? string.Empty;
                        }                        

                        if (fbUserId.IsNotNullAndNotEmpty())
                        {
                            fbUserId = UserManager.FACEBOOK_PREFIX + fbUserId.Trim();

                            if (Member.IsMember(fbUserId))
                            {
                                newMember = Member.GetMemberFromLoginName(fbUserId);
                            }
                            else
                            {
                                newMember = UserManager.CreateFacebookSubscriber(fbUserId, fbUserName, gender, location);
                            }

                        }
                    }
                }
                else
                {
                    Log.Add(LogTypes.Notify, -1, "Facebook.ashx(pblogon) Access token is null or empty");
                }
            }

            return newMember;
        }

       

       
    }
}